<template>
  <div class="statistics-index">
    <div class="statistics-container">
      <div class="stat-card">
        <h3>总用户数</h3>
        <p class="stat-value">{{ userCount }}</p>
      </div>
      <div class="stat-card">
        <h3>总商家数</h3>
        <p class="stat-value">{{ shopCount }}</p>
      </div>
      <div class="stat-card">
        <h3>总订单数</h3>
        <p class="stat-value">{{ orderCount }}</p>
      </div>
      <div class="stat-card">
        <h3>总销售额</h3>
        <p class="stat-value">{{ totalSales }}</p>
      </div>
    </div>
    
    <!-- 左右分栏布局 -->
    <div class="charts-wrapper">
      <!-- 左侧地图容器 -->
      <div class="chart-item map-container">
        <h3>区域分布</h3>
        <div id="mapChart" class="chart-content"></div>
      </div>
      
      <!-- 右侧趋势图表 -->
      <div class="chart-right">
        <div class="chart-item">
          <h3>用户年龄分布</h3>
          <div id="agePieChart" class="chart-content"></div>
        </div>
      </div>
    </div>

    <div class="charts-container">
      <div id="orderTrendChart" class="chart"></div>
      <div id="salesTrendChart" class="chart"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import * as echarts from 'echarts';

// 统计数据
const userCount = ref(0);
const shopCount = ref(0);
const orderCount = ref(0);
const totalSales = ref(0);

// 图表实例
let orderTrendChart = null;
let salesTrendChart = null;
let mapChart = null;
let agePieChart = null; 

// 加载统计数据
const loadStatisticsData = async () => {
  try {
    const userCountRes = await axios.get('/api/statistics/user-count');
    userCount.value = userCountRes.data.data;

    const shopCountRes = await axios.get('/api/statistics/shop-count');
    shopCount.value = shopCountRes.data.data;

    const orderCountRes = await axios.get('/api/statistics/order-count');
    orderCount.value = Math.floor(orderCountRes.data.data); // 转换为整数

    const totalSalesRes = await axios.get('/api/statistics/total-sales');
    totalSales.value = totalSalesRes.data.data;
  } catch (error) {
    console.error('加载统计数据失败:', error);
  }
};

// 加载趋势数据并初始化图表
const loadTrendDataAndInitCharts = async () => {
  try {
    // 加载订单趋势数据
    const orderTrendRes = await axios.get('/api/statistics/order-trend');
    const orderTrendData = orderTrendRes.data.data;

    // 确保订单数量为整数
    orderTrendData.forEach(item => {
      item.count = Math.floor(item.count);
    });

    // 加载销售趋势数据
    const salesTrendRes = await axios.get('/api/statistics/sales-trend');
    const salesTrendData = salesTrendRes.data.data;
    
    // 加载用户年龄数据
    const userAgeRes = await axios.get('/api/statistics/user-age');
    // 转换后端返回的数据格式以匹配ECharts要求的格式
    const userAgeData = (userAgeRes.data.data || []).map(item => ({
      name: item.ageGroup,
      value: item.count
    }));

    // 检查数据是否为空
    if (userAgeData.length === 0) {
      console.warn('没有获取到用户年龄数据');
      // 创建一个默认数据，避免图表显示异常
      userAgeData.push({ name: '暂无数据', value: 1 });
    }

    // 初始化订单趋势图表
    if (orderTrendChart) {
      orderTrendChart.dispose();
    }
    orderTrendChart = echarts.init(document.getElementById('orderTrendChart'));
    orderTrendChart.setOption({
      title: { text: '订单趋势' },
      tooltip: { trigger: 'axis' },
      xAxis: { data: orderTrendData.map(item => item.month) },
      yAxis: {
        axisLabel: {
          formatter: '{value}'
        },
        minInterval: 1
      },
      series: [{ name: '订单数', type: 'line', data: orderTrendData.map(item => item.count) }]
    });

    // 初始化销售趋势图表
    if (salesTrendChart) {
      salesTrendChart.dispose();
    }
    salesTrendChart = echarts.init(document.getElementById('salesTrendChart'));
    salesTrendChart.setOption({
      title: { text: '销售趋势' },
      tooltip: { trigger: 'axis' },
      xAxis: { data: salesTrendData.map(item => item.month) },
      yAxis: {
        axisLabel: {
          formatter: '{value}'
        },
        minInterval: 1
      },
      series: [{ name: '销售额', type: 'line', data: salesTrendData.map(item => item.total_sales) }]
    });
    
    // 初始化年龄分布饼图
    const chartContainer = document.getElementById('agePieChart');
    if (chartContainer) {
      if (agePieChart) {
        agePieChart.dispose();
      }
      agePieChart = echarts.init(chartContainer);
      agePieChart.setOption({
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
        },
        series: [{
          name: '年龄分布',
          type: 'pie',
          radius: '60%',
          center: ['50%', '50%'],
          data: userAgeData,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            },
            label: {
              formatter: '{b}: {d}%'
            }
          }
        }]
      });
    }

    // 窗口大小改变时，重新调整图表大小
    const handleResize = () => {
      if (orderTrendChart) orderTrendChart.resize();
      if (salesTrendChart) salesTrendChart.resize();
      if (agePieChart) agePieChart.resize();
    };
    
    window.addEventListener('resize', handleResize);
  } catch (error) {
    console.error('加载趋势数据并初始化图表失败:', error);
  }
};



// 加载商家地理数据并初始化地图
const loadShopGeoDataAndInitMap = async () => {
  try {
    // 先加载地图数据 - 改为加载桂林地图
    const mapDataRes = await axios.get('/map/guilin.json');
    const guilinMapData = mapDataRes.data;

    // 注册桂林地图
    try {
      echarts.registerMap('guilin', guilinMapData);
      console.log('桂林地图数据注册成功');
    } catch (error) {
      console.error('桂林地图数据注册失败:', error);
    }

    // 加载商家地理数据
    const shopGeoRes = await axios.get('/api/statistics/shop-geo-distribution');
    
    // 地址标准化处理函数 - 只保留桂林的区域
    const normalizeAddress = (address) => {
      // 检查地址是否有效
      if (!address || typeof address !== 'string') {
        return '未知地区';
      }
      
      // 桂林市区县列表
      const guilinDistricts = [
        '秀峰区', '叠彩区', '象山区', '七星区', '雁山区', '临桂区',
        '阳朔县', '灵川县', '全州县', '兴安县', '永福县', '灌阳县',
        '龙胜各族自治县', '资源县', '平乐县', '荔浦市', '恭城瑶族自治县'
      ];
      
      // 检查是否包含桂林的区县
      for (const district of guilinDistricts) {
        if (address.includes(district)) {
          return district;
        }
      }
      
      // 检查是否包含"桂林"
      if (address.includes('桂林')) {
        return '桂林市';
      }
      
      // 默认返回未知地区
      return '未知地区';
    };
    
    // 过滤掉无效数据并转换数据格式
    const rawData = shopGeoRes.data.data || [];
    const shopGeoData = rawData
      .filter(item => item && item.address && item.count !== undefined)
      .map(item => ({
        name: normalizeAddress(item.address),
        value: item.count
      }))
      .filter(item => item.name !== '未知地区'); // 过滤掉未知地区

    // 初始化地图图表
    if (mapChart) {
      mapChart.dispose();
    }
    mapChart = echarts.init(document.getElementById('mapChart'));

    // 设置地图选项
    mapChart.setOption({
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c}家'
      },
      visualMap: {
        min: 0,
        max: Math.max(...shopGeoData.map(item => item.value), 10),
        left: 'left',
        top: 'bottom',
        text: ['高', '低'],
        calculable: true,
        inRange: {
          color: ['#e0f7fa', '#00acc1']  
        }
      },
      series: [{
        name: '商家数量',
        type: 'map',
        map: 'guilin',
        roam: true,
        label: {
          show: false
        },
        emphasis: {
          itemStyle: {
            areaColor: '#ff7043',
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          },
          label: {
            show: true,
            fontSize: 14,
            fontWeight: 'bold'
          }
        },
        itemStyle: {
          areaColor: '#e0f7fa',
          borderColor: '#fff',
          borderWidth: 1
        },
        data: shopGeoData
      }]
    });
  } catch (error) {
    console.error('加载商家地理数据并初始化地图失败:', error);
  }
};

// 页面加载时执行
onMounted(() => {
  loadStatisticsData();
  loadTrendDataAndInitCharts();
  loadShopGeoDataAndInitMap();
});
</script>

<style scoped>
.statistics-index {
  padding: 20px;
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
  background-color: #f5f7fa;
  min-height: 100vh;
}

h2 {
  color: #2c3e50;
  font-size: 28px;
  margin-bottom: 25px;
  padding-bottom: 12px;
  border-bottom: 3px solid #3498db;
  text-align: center;
}

.statistics-container {
  padding: 20px 0;
  display: flex;
  flex-wrap: nowrap;  /* 不允许换行 */
  gap: 15px;
  justify-content: center;
  overflow-x: auto;  /* 当屏幕太小时允许水平滚动 */
}

.stat-card {
  flex: 1 1 200px;  /* 调整flex属性 */
  max-width: 220px;  /* 减小最大宽度 */
  padding: 20px;
  margin: 10px 0;
  background-color: #fff;
  border-radius: 12px;
  text-align: center;
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.stat-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 5px;
  background: linear-gradient(90deg, #3498db, #2ecc71);
}

.stat-card:hover {
  transform: translateY(-8px);
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.12);
}

.stat-card h3 {
  color: #7f8c8d;
  font-size: 18px;
  margin-bottom: 15px;
  font-weight: 500;
}

.stat-value {
  font-size: 32px;
  font-weight: bold;
  color: #3498db;
  margin: 0;
  transition: color 0.3s ease;
}

.stat-card:hover .stat-value {
  color: #2ecc71;
}

.charts-wrapper {
  display: flex;
  margin-top: 30px;
  gap: 20px;
  flex-wrap: wrap;
}

.chart-item {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08);
  padding: 25px;
  margin: 10px 0;
  flex: 1;
  min-width: 300px;
  transition: all 0.3s ease;
}

.chart-item:hover {
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.12);
}

.chart-item h3 {
  color: #2c3e50;
  font-size: 20px;
  margin-bottom: 20px;
  font-weight: 500;
  padding-bottom: 10px;
  border-bottom: 1px solid #ecf0f1;
}

.map-container {
  flex: 1;
  min-width: 300px;
}

.chart-right {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.chart-content {
  width: 100%;
  height: 300px;
}

.charts-container {
  display: flex;
  gap: 20px;
  margin-top: 30px;
  flex-wrap: wrap;
}

.chart {
  flex: 1;
  min-width: 300px;
  height: 350px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08);
  padding: 25px;
  margin: 10px 0;
  transition: all 0.3s ease;
}

.chart:hover {
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.12);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .statistics-container {
    justify-content: center;
  }
  
  .stat-card {
    flex: 1 1 100%;
    max-width: 100%;
  }
  
  .charts-wrapper {
    flex-direction: column;
  }
  
  .chart-right {
    flex: 1;
  }
  
  .charts-container {
    flex-direction: column;
  }
}
</style>